/**
 * SQL模板管理器 - 导入导出模块
 * 负责模板的导入导出功能
 */

// 扩展TemplateManager类的导入导出功能
Object.assign(TemplateManager.prototype, {
    // 导入模态框管理
    showImportModal() {
        if (this.importModal) {
            this.resetImportForm();
            this.importModal.classList.remove('hidden');
        }
    },

    hideImportModal() {
        if (this.importModal) {
            this.importModal.classList.add('hidden');
            this.resetImportForm();
        }
    },

    resetImportForm() {
        if (this.importFileInput) {
            this.importFileInput.value = '';
        }
        if (this.selectedFileName) {
            this.selectedFileName.textContent = '未选择文件';
        }
        if (this.skipExisting) {
            this.skipExisting.checked = true;
        }
        if (this.validateFormat) {
            this.validateFormat.checked = true;
        }
        if (this.previewSection) {
            this.previewSection.classList.add('hidden');
        }
        if (this.importProgress) {
            this.importProgress.classList.add('hidden');
        }
        if (this.startImportBtn) {
            this.startImportBtn.disabled = true;
        }
        this.selectedFile = null;
        this.importData = null;
    },

    // 文件选择处理
    handleFileSelect(event) {
        const file = event.target.files[0];
        this.processSelectedFile(file);
    },

    handleDragOver(event) {
        event.preventDefault();
        event.stopPropagation();
        this.fileDropZone.classList.add('border-blue-500', 'bg-blue-50', 'dark:bg-blue-900/20');
    },

    handleFileDrop(event) {
        event.preventDefault();
        event.stopPropagation();
        this.fileDropZone.classList.remove('border-blue-500', 'bg-blue-50', 'dark:bg-blue-900/20');
        
        const files = event.dataTransfer.files;
        if (files.length > 0) {
            this.processSelectedFile(files[0]);
        }
    },

    processSelectedFile(file) {
        if (!file) {
            return;
        }

        // 检查文件类型
        if (file.type !== 'application/json' && !file.name.endsWith('.json')) {
            this.showError('请选择JSON格式的文件');
            return;
        }

        // 检查文件大小（限制为10MB）
        if (file.size > 10 * 1024 * 1024) {
            this.showError('文件大小不能超过10MB');
            return;
        }

        this.selectedFile = file;
        this.selectedFileName.textContent = file.name;

        // 读取文件内容
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const content = e.target.result;
                const data = JSON.parse(content);
                
                if (this.validateFormat.checked) {
                    const validation = this.validateTemplatesFormat(data);
                    if (!validation.valid) {
                        this.showError(`文件格式验证失败: ${validation.error}`);
                        return;
                    }
                }
                
                this.importData = data;
                this.showPreview(data);
                this.startImportBtn.disabled = false;
                
            } catch (error) {
                console.error('文件解析失败:', error);
                this.showError('文件格式不正确，请检查JSON格式');
            }
        };
        
        reader.onerror = () => {
            this.showError('文件读取失败');
        };
        
        reader.readAsText(file);
    },

    // 格式验证
    validateTemplatesFormat(data) {
        if (!Array.isArray(data)) {
            return { valid: false, error: '数据必须是数组格式' };
        }

        if (data.length === 0) {
            return { valid: false, error: '文件中没有模板数据' };
        }

        for (let i = 0; i < data.length; i++) {
            const template = data[i];
            
            if (!template.id || typeof template.id !== 'string') {
                return { valid: false, error: `第${i + 1}个模板缺少有效的id字段` };
            }
            
            if (!template.description || typeof template.description !== 'string') {
                return { valid: false, error: `第${i + 1}个模板缺少有效的description字段` };
            }
            
            if (!template.sql_template || typeof template.sql_template !== 'string') {
                return { valid: false, error: `第${i + 1}个模板缺少有效的sql_template字段` };
            }
            
            // 验证parameters字段（可选）
            if (template.parameters !== undefined) {
                if (typeof template.parameters === 'string') {
                    try {
                        JSON.parse(template.parameters);
                    } catch (e) {
                        return { valid: false, error: `第${i + 1}个模板的parameters字段不是有效的JSON字符串` };
                    }
                } else if (!Array.isArray(template.parameters)) {
                    return { valid: false, error: `第${i + 1}个模板的parameters字段必须是数组或JSON字符串` };
                }
            }
        }

        return { valid: true };
    },

    // 预览显示
    showPreview(data) {
        const previewHtml = `
            <div class="space-y-4">
                <div class="flex justify-between items-center">
                    <h4 class="font-medium text-gray-900 dark:text-white">预览内容</h4>
                    <span class="text-sm text-gray-500 dark:text-gray-400">共 ${data.length} 个模板</span>
                </div>
                <div class="max-h-64 overflow-y-auto space-y-2">
                    ${data.slice(0, 5).map((template, index) => `
                        <div class="border border-gray-200 dark:border-gray-600 rounded-lg p-3">
                            <div class="flex justify-between items-start mb-2">
                                <h5 class="font-medium text-gray-900 dark:text-white text-sm">${this.escapeHtml(template.id)}</h5>
                                <span class="text-xs text-gray-500 bg-gray-100 dark:bg-gray-600 px-2 py-1 rounded">#${index + 1}</span>
                            </div>
                            <p class="text-xs text-gray-600 dark:text-gray-400 mb-2">${this.escapeHtml(template.description.substring(0, 100))}${template.description.length > 100 ? '...' : ''}</p>
                            <div class="bg-gray-50 dark:bg-gray-700 rounded p-2">
                                <code class="text-xs text-gray-800 dark:text-gray-200">${this.escapeHtml(template.sql_template.substring(0, 80))}${template.sql_template.length > 80 ? '...' : ''}</code>
                            </div>
                        </div>
                    `).join('')}
                    ${data.length > 5 ? `<div class="text-center py-2 text-sm text-gray-500 dark:text-gray-400">还有 ${data.length - 5} 个模板...</div>` : ''}
                </div>
            </div>
        `;
        
        this.previewContent.innerHTML = previewHtml;
        this.previewSection.classList.remove('hidden');
    },

    // 开始导入
    async startImport() {
        if (!this.importData || !Array.isArray(this.importData)) {
            this.showError('没有有效的导入数据');
            return;
        }

        // 显示进度条
        this.importProgress.classList.remove('hidden');
        this.startImportBtn.disabled = true;
        
        const templates = this.importData;
        const skipExisting = this.skipExisting.checked;
        let successCount = 0;
        let skipCount = 0;
        let errorCount = 0;
        
        this.updateProgress(0, '开始导入...');
        
        for (let i = 0; i < templates.length; i++) {
            const template = templates[i];
            const percent = ((i + 1) / templates.length) * 100;
            
            this.updateProgress(percent, `导入模板: ${template.id}`);
            
            try {
                // 检查模板是否已存在
                const existingTemplate = this.templates.find(t => t.id === template.id);
                if (existingTemplate && skipExisting) {
                    skipCount++;
                    continue;
                }
                
                // 处理parameters字段
                let parametersArray;
                if (Array.isArray(template.parameters)) {
                    parametersArray = template.parameters;
                } else if (typeof template.parameters === 'string') {
                    try {
                        parametersArray = JSON.parse(template.parameters);
                    } catch (e) {
                        parametersArray = [];
                    }
                } else {
                    parametersArray = [];
                }
                
                // 发送API请求
                const response = await authenticatedFetch('/api/v0/sql_templates', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        id: template.id,
                        description: template.description,
                        sql_template: template.sql_template,
                        parameters: parametersArray,
                        plotly_code: template.plotly_code || ''
                    })
                });
                
                if (response.ok) {
                    successCount++;
                } else {
                    errorCount++;
                    console.error(`导入模板 ${template.id} 失败:`, await response.text());
                }
            } catch (error) {
                errorCount++;
                console.error(`导入模板 ${template.id} 时发生错误:`, error);
            }
            
            // 添加小延迟以显示进度
            await new Promise(resolve => setTimeout(resolve, 100));
        }
        
        this.updateProgress(100, '导入完成');
        
        // 显示结果
        const message = `导入完成！成功: ${successCount}, 跳过: ${skipCount}, 失败: ${errorCount}`;
        if (errorCount > 0) {
            this.showError(message);
        } else {
            this.showSuccess(message);
        }
        
        // 刷新模板列表
        await this.loadTemplates();
        
        // 延迟关闭模态框
        setTimeout(() => {
            this.hideImportModal();
        }, 2000);
    },

    // 更新进度
    updateProgress(percent, text) {
        if (this.progressBar) {
            this.progressBar.style.width = `${percent}%`;
        }
        if (this.progressText) {
            this.progressText.textContent = `${Math.round(percent)}%`;
            if (text) {
                this.progressText.textContent += ` - ${text}`;
            }
        }
    },

    // 导出模板
    async exportTemplates() {
        try {
            if (this.templates.length === 0) {
                this.showError('没有可导出的模板');
                return;
            }
            
            // 准备导出数据
            const exportData = this.templates.map(template => {
                let parameters;
                try {
                    // 尝试解析parameters字符串为JSON数组
                    parameters = template.parameters ? JSON.parse(template.parameters) : [];
                } catch (error) {
                    console.warn(`模板 ${template.id} 的parameters格式不正确，使用空数组:`, error);
                    parameters = [];
                }
                
                return {
                    id: template.id,
                    description: template.description,
                    sql_template: template.sql_template,
                    parameters: parameters,
                    plotly_code: template.plotly_code
                };
            });
            
            // 创建下载链接
            const dataStr = JSON.stringify(exportData, null, 2);
            const dataBlob = new Blob([dataStr], { type: 'application/json' });
            const url = URL.createObjectURL(dataBlob);
            
            // 创建下载链接并触发下载
            const link = document.createElement('a');
            link.href = url;
            link.download = `sql_templates_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 清理URL对象
            URL.revokeObjectURL(url);
            
            this.showSuccess(`成功导出 ${exportData.length} 个模板`);
        } catch (error) {
            console.error('导出失败:', error);
            this.showError('导出失败，请重试');
        }
    }
});